<?php
/**
 * Controller_Admin_City
 *
 * Класс Controller_Admin_City отвечает за обработку городов в админке
 *
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.0
 */
class Controller_Admin_City extends Controller_Admin {

	protected $countryCode = null;
  protected $cityNameStart = null;
  
	/**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
		Service_Debug::setDebug();
		$this->addCss('cms/city.css');
		$this->addJs('cms/city.js');
		switch ($this->arrRequest[2]) {
			case '': case 'list':
		    if (isset($_GET['cityNameStart'])) $this->cityNameStart = Service_Escape::absolutelyEscapeString($_GET['cityNameStart']);
		    $this->actionList();
				break;
		  case 'country': //фильтрация городов по стране
		    if (!isset($this->arrRequest[3])) { //проверяем наличие параметров
				  $this->show404Error();
				  break;
				}
				if (isset($_GET['cityNameStart'])) $this->cityNameStart = Service_Escape::absolutelyEscapeString($_GET['cityNameStart']);
				$this->countryCode = Service_Escape::absolutelyEscapeString($this->arrRequest[3]);
				if (!$this->countryCode) User_Session::moveTo(W_ADMIN . 'cities/?p=' . $this->pageNum); //idCountry=0 => ВСЕ_СТРАНЫ
  		  $this->actionList();
				break;
			case 'edit':
				  $cityId = intval($this->arrRequest[3]);
					$objCity = new City($cityId);
					if ($objCity->id) $this->actionEdit($objCity);
					else $this->setError(404);
				break;
			case 'merge':
				  $cityId = intval($this->arrRequest[3]);
					$objCity = new City($cityId);
					if ($objCity->id) $this->actionMerge($objCity);
					else $this->setError(404);
				break;
			default:
				$this->setError(404);
				break;
		}
	}

	/**
	 * Выводим все города для администрирования
	 *
	 * @param int $idWorldPart - ID части света
	 */
	public function actionList() {
    $conditions = "1 ";
    if ($this->countryCode) $conditions .= " AND `city`.`country_code` = '" . $this->countryCode . "' ";
		if ($this->cityNameStart) $conditions .= " AND (`city`.`city_final_name_ru` LIKE '" . $this->cityNameStart . "%' OR `city`.`city_final_name_en` LIKE '" . $this->cityNameStart . "%') ";
		$objCity = new City();
	  $arrCities = $objCity->find('all', array('order' => '`city_final_name_ru` ASC, `city_final_name_en` ASC', 'limit' => $this->pageLimit, 'offset' => ($this->pageNum - 1) * $this->pageLimit, 'conditions' => $conditions));
    $this->elementsInListAmount = $objCity->count($conditions); //получаем общее кол-во стран;
		
    $objViewCity = new View_City();
    $this->title = $this->pageHead = 'Список городов';
    //$this->addJs('сity.js');
    		
    $this->showHeader();
	    echo '<div id="mainAdministration">';
     		$objViewCity->showListForAdmin($arrCities);
     		$this->showPages();
	    echo '</div>';
		$this->showFooter();
	}
	
  /**
   * Выводит страницу редактирования страны
   * 
   * @param City $objCity - объект города для редактирования
   */
  public function actionEdit(City $objCity) {
		$editId = $objCity->id;
		if (!empty($_POST['basic_city_id'])) {
			$basicCityId = intval($_POST['basic_city_id']);
			if ($objCity->mergeWithOldCity($basicCityId)) User_Session::moveTo(W_ADMIN . 'cities/edit/' . $objCity->id .  '/', 'Информация совмещена', 1);
			else User_Session::moveTo(W_ADMIN . 'cities/edit/' . $objCity->id .  '/', 'Что-то прошло не так');
		}
  	if (isset($_POST['City'])) {
			$objCity = new City($_POST['City']);
			if ($objCity->id != $editId) User_Session::moveTo(View_Base::getLanguageUrl(W_ADMIN) . 'cities/', Service_Translate::getText('Недопустимое действие'));
			if ($objCity->save()) User_Session::moveTo(W_ADMIN . 'cities/', 'Город успешно сохранен', 1);
		}
		$objCountry= new Country($objCity->getField('country_code'));
		$arrOldCities = $objCountry->getOldUncopiedCities();
  	
  	$objViewCity = new View_City();
  	$this->pageHead = $this->title = 'Редактирование города "' . View_City::getName($objCity->tableFields) . '"';
    $this->addWysiwygMetas();
  	$this->showHeader();
  	  $objViewCity->showMergeForm($objCity, $arrOldCities);
      $objViewCity->showEditForm($objCity);
    $this->showFooter();
  }
  
  /**
   * Выводит страницу совмещения гостиниц города
   * 
   * @param City $objCity - объект города для вывода списков
   */
  public function actionMerge(City $objCity) {
  	$arrOldHotels = $objCity->getOldUncopiedHotels();
  	$objHotel = new Hotel();
  	$arrNewHotels = $objHotel->find('all', array('select' => "`ID_hotel`, `hotel_name_ru`, `hotel_name_en`", 'conditions' => "`ID_city` = '" . $objCity->id . "' AND `is_filled` = 0", 'order' => "`hotel_name_en` ASC, `hotel_name_ru` ASC"));
  	
  	$objViewHotel = new View_Hotel();
  	$cityName = View_City::getName($objCity->tableFields);
  	if (empty($cityName)) $cityName = View_City::getName($objCity->tableFields);
  	$this->pageHead = $this->title = 'Совмещение гостиниц города "' . $cityName . '"';
    
  	$this->showHeader();
      $objViewHotel->showMergeLists($arrNewHotels, $arrOldHotels);
    $this->showFooter();
  }
  
  /**
   * Выводит левую часть
   *
   */
  public function showLeft() {
  	$objCountry = new Country();
  	$arrCountries = $objCountry->find('all', array('order' => '`country_final_name_ru` ASC, `country_final_name_en` ASC'));
  	$objViewCity = new View_City();
  	echo '<div id="left">';
      $objViewCity->showCountryFilterForAdmin($arrCountries, $this->countryCode);
      $this->showAdminMenu();
  	echo '</div>';
  }
  
}
?>